import os
from datetime import datetime
from celery import shared_task
from models.version import Version
from models.project import Project
from services.fastlane import FastlaneService
from services.app_store_connect import AppStoreConnectService
from extensions import db
from config import Config

@shared_task(bind=True)
def process_version(self, version_id: int):
    """处理版本创建任务
    
    Args:
        version_id: 版本ID
    """
    version = Version.query.get(version_id)
    if not version:
        return {'success': False, 'error': 'Version not found'}
    
    project = version.project
    if not project:
        return {'success': False, 'error': 'Project not found'}
    
    try:
        # 更新状态为处理中
        version.status = 'processing'
        db.session.commit()
        
        # 创建工作目录
        workspace_path = os.path.join(Config.WORKSPACE_ROOT, f'project_{project.id}', f'version_{version.id}')
        os.makedirs(workspace_path, exist_ok=True)
        
        # 初始化服务
        fastlane_service = FastlaneService(
            workspace_path=workspace_path,
            mock_mode=Config.MOCK_MODE
        )
        
        asc_service = AppStoreConnectService(
            key_id=project.asc_key_id or Config.ASC_KEY_ID,
            key_file=project.asc_key_file or Config.ASC_KEY_FILE,
            issuer_id=project.asc_issuer_id or Config.ASC_ISSUER_ID,
            mock_mode=Config.MOCK_MODE
        )
        
        # 1. 下载 metadata
        version.download_status = 'processing'
        db.session.commit()
        
        download_result = fastlane_service.download_metadata(
            username=project.username,
            bundle_id=project.bundle_id,
            output_path=os.path.join(workspace_path, 'metadata')
        )
        
        if not download_result['success']:
            raise Exception(f"Failed to download metadata: {download_result.get('error')}")
        
        version.download_status = 'success'
        version.metadata_path = download_result['metadata_path']
        db.session.commit()
        
        # 2. 创建 App Store 版本
        create_result = asc_service.create_new_version(
            bundle_id=project.bundle_id,
            version_number=version.version_number
        )
        
        if not create_result['success']:
            raise Exception(f"Failed to create App Store version: {create_result.get('error')}")
        
        version.asc_version_id = create_result['version_id']
        db.session.commit()
        
        # 3. 上传 metadata
        version.upload_status = 'processing'
        db.session.commit()
        
        upload_result = fastlane_service.upload_metadata(
            username=project.username,
            bundle_id=project.bundle_id,
            version=version.version_number,
            metadata_path=version.metadata_path
        )
        
        if not upload_result['success']:
            raise Exception(f"Failed to upload metadata: {upload_result.get('error')}")
        
        version.upload_status = 'success'
        version.status = 'success'
        version.completed_at = datetime.utcnow()
        db.session.commit()
        
        return {
            'success': True,
            'version_id': version.id,
            'asc_version_id': version.asc_version_id
        }
        
    except Exception as e:
        version.status = 'failed'
        version.error_message = str(e)
        version.completed_at = datetime.utcnow()
        db.session.commit()
        
        return {
            'success': False,
            'error': str(e)
        }
